import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment/moment';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import './index.scss';

/**
 * 组件： 文章页
 */
class Article extends React.PureComponent {
  static propTypes = {
    title: PropTypes.string,
    desc: PropTypes.element,
    createTime: PropTypes.string,
  };
  static defaultProps = {
    title: '',
    desc: '',
    createTime: ''
  };
  constructor(props) {
    super(props);
    this.state = {
      favorState: false,
      favor: props.favor
    };
    this.doFavor = ::this.doFavor;
  }
  componentWillReceiveProps(nextPorp) {
    this.setState({
      favor: nextPorp.favor,
    });
  }
  doFavor() {
    if (!this.state.favorState) {
      const api = new Api({
        method: 'PATCH',
        path: `${this.props.favorPath}`,
        success: () => {
          this.setState(prevState => ({
            favorState: !prevState.favorState,
            favor: prevState.favor + 1
          }));
        },
        error: (msg) => {
          const buttons = [
            {
              label: '知道了',
              onClick: () => {},
            },
          ];
          dialog.open('提示', msg, buttons, 'center');
        }
      });
      api.run();
    }
  }
  render() {
    const { title, createTime, desc } = this.props;
    const { favorState, favor } = this.state;
    return (
      <div className="article-detail-content-wrap">
        <div className="article-header">
          <div className="artical-title">{title || ''}</div>
          <div className="extra-info">
            <span className="publish-time">{`发布时间： ${createTime ? moment(createTime).format('YYYY年MM月DD日') : ''}`}</span>
            {favor > -1 &&
            <span className="favor">{`赞： (${favor || ''})`}</span>
            }
            {favor > -1 &&
            <a
              href="javascript:void(0)"
              onClick={this.doFavor}
              className={`favor-action ${favorState ? 'select' : ''}`}
            >
              {''}
            </a>
            }
          </div>
        </div>
        <div className="article-content">
          {
            desc || ''
          }
        </div>
      </div>
    );
  }
}

export default Article;
